import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
import util from '@/libs/util'
import router from '@/router'
import i18n from '../../i18n'


// 记录和显示错误
function errorLog(error) {

  // 打印到控制台
  if (process.env.NODE_ENV === 'development') {
    console.error(error)
  }

  // 显示提示
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  });
}

function isError(result) {

  if (result.code != 0) {
    return true;
  }
  return false;
}

function isTokenError(re) {
  switch (re.code) {
    case 1000:
    case 1001:
    case 1002:
      return true;
  }

  return false;
}

const service = axios.create({
  baseURL: process.env.VUE_APP_API,
  timeout: 5000,
});

// 请求拦截
service.interceptors.request.use(

  config => {

    if (config.data) {
      if (config.data.search) {
        Object.keys(config.data.search).forEach(key=>{
          var value = config.data.search[key];
          if (Array.isArray(value) && value.length == 0) {
            delete config.data.search[key];
          }
          else if (value === '') {
            delete config.data.search[key]
          }
           
        })
      }
      // let newData = JSON.parse(config.data)
      // console.log(newData)
    }
    
    config.headers['locale'] = /zh/i.test(i18n.locale) ? 'zh_CN' : 'en';
    config.headers['Authorization'] = 'Bearer ' + util.cookies.get('Authorization')
    return config
  },
  error => {
    console.error(error)
    Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    // dataAxios 是 axios 返回数据中的 data
    const result = response.data

    if (isError(result)) {
      // 错误返回

      if (/mchmember\/logout$/.test(response.config.url)) {
        // 如果是登出接口, 则不弹窗
      }
      else {

        // Token 失效
        if (isTokenError(result)) {
          // 登出逻辑
          store.dispatch('d2admin/account/logout', {}, { root: true });
        }

        if (result.code == 1005) {

        }
        else {
          errorLog(result);
        }

      }

      return Promise.reject(result)
    }
    else {
      // console.log(result);
      return result.data;
    }
  },
  error => {

    if (error && error.response) {
      switch (error.response.status) {
        case 400: error.message = '请求错误'; break
        case 401: error.message = '未授权，请登录'; break
        case 403: error.message = '拒绝访问'; break
        case 404: error.message = `请求地址出错: ${error.response.config.url}`; break
        case 408: error.message = '请求超时'; break
        case 500: error.message = '服务器内部错误'; break
        case 501: error.message = '服务未实现'; break
        case 502: error.message = '网关错误'; break
        case 503: error.message = '服务不可用'; break
        case 504: error.message = '网关超时'; break
        case 505: error.message = 'HTTP版本不受支持'; break
        default: break
      }
    }
    errorLog(error)
    return Promise.reject(error)
  }
)


window.service = service;

export default service;